package com.ftd.controller.filter;


import com.ftd.util.Constant;
import com.ftd.util.DigestUtil;
import com.ftd.viewmodel.ApiError;
import com.alibaba.fastjson.JSON;

import org.apache.shiro.util.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Peter on 2016-07-15.
 */
public class ApiAuthenticatingFilter implements Filter {

    private static final Logger logger = LoggerFactory
            .getLogger(ApiAuthenticatingFilter.class);


    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String url = ((HttpServletRequest) request).getRequestURL().toString();

        //如果是登陆的url,则不需要验证身份
        if (url.contains("saveInBackground") || url.contains("memberCard/new.do")) {
            chain.doFilter(request, response);
            return;
        }

        //获取验证身份的token
        String authHeader = request.getParameter(Constant.Authorization);
        if (authHeader == null) {
            logger.info("authHeader is null");
        } else {
            logger.info("authHeader:" + authHeader);
        }

        if (!StringUtils.isEmpty(authHeader)) {
            String[] principals = getPrincipalsAndCredentials(authHeader);
            Integer userId = Integer.valueOf(principals[0]);
            logger.warn("customerId" + userId);
            ThreadContext.put(Constant.USERID, userId);
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(JSON.toJSONString(ApiError.unAuthenticate()));
        }

    }

    public void destroy() {
        ThreadContext.remove(Constant.USERID);

    }

    protected String[] getPrincipalsAndCredentials(String authorizationHeader) {
        String[] authTokens = authorizationHeader.split(" ");
        String token = authTokens[1];
        String decoded = DigestUtil.Decrypt(token);
        return decoded.split(":", 2);
    }

}
